﻿namespace CodeSHARPer.Avalondock
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using AvalonDock.Layout;

    class LayoutInitializer : ILayoutUpdateStrategy
    {
        public bool BeforeInsertAnchorable(LayoutRoot layout, LayoutAnchorable anchorableToShow, ILayoutContainer destinationContainer)
        {
            //AD wants to add the anchorable into destinationContainer
            //just for test provide a new anchorablepane 
            //if the pane is floating let the manager go ahead
            LayoutAnchorablePane destPane = destinationContainer as LayoutAnchorablePane;
            if (destinationContainer != null &&
                destinationContainer.FindParent<LayoutFloatingWindow>() != null)
                return false;

            var toolsPane = layout.Descendents().OfType<LayoutAnchorablePane>()
                .Where(d => d != null && !string.IsNullOrEmpty(d.Name) && 
                    (d.Name.Equals("RecentFiles", StringComparison.OrdinalIgnoreCase))).FirstOrDefault();

            if (toolsPane != null)
            {
                if (toolsPane.Children.Where(c => c.ContentId.Equals(anchorableToShow.ContentId, StringComparison.OrdinalIgnoreCase)).Count() == 0)
                {
                    toolsPane.Children.Add(anchorableToShow);
                    return true;
                }
            }

            return false;
        }


        public void AfterInsertAnchorable(LayoutRoot layout, LayoutAnchorable anchorableShown)
        {
        }


        public bool BeforeInsertDocument(LayoutRoot layout, LayoutDocument anchorableToShow, ILayoutContainer destinationContainer)
        {
            return false;
        }

        public void AfterInsertDocument(LayoutRoot layout, LayoutDocument anchorableShown)
        {

        }
    }
}
